<template>
  <div class="app-container">
    <!-- 状态卡片 -->
    <div class="status-cards">
      <el-card class="status-card not-started">
        <div class="status-content">
          <div class="status-title">未开始</div>
          <div class="status-count">{{ notStartedCount }}</div>
        </div>
      </el-card>
      <el-card class="status-card in-progress">
        <div class="status-content">
          <div class="status-title">进行中</div>
          <div class="status-count">{{ inProgressCount }}</div>
        </div>
      </el-card>
      <el-card class="status-card completed">
        <div class="status-content">
          <div class="status-title">已完成</div>
          <div class="status-count">{{ successNumber }}</div>
        </div>
      </el-card>
    </div>

    <div class="header-bar" style="justify-content: flex-end;">
      <el-input
        placeholder="请输入需求编号/名称/关联合同"
        style="width: 240px; float: right; margin-bottom: 10px;"
        v-model="queryParams.keyWord"
        @keyup.enter="handleSearch"
        clearable
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch"></el-button>
        </template>
      </el-input>
    </div>

    <el-table 
      :data="productionList" 
      style="width: 100%" 
      :loading="loading"
      border
    >
      <el-table-column prop="dno" label="需求编号" align="left" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="dname" label="需求名称" align="left" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="coName" label="关联合同" align="left" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="materialName" label="物料" align="left" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="productionNumber" label="生产加工单数" align="left" width="120"></el-table-column>
      <el-table-column prop="successNumber" label="完成数量" align="left" width="120">
        <template #header>
          <div class="header-search-container">
            <span>完成数量</span>
            <el-popover placement="bottom" width="250" trigger="click">
              <template #reference>
                <el-icon class="search-icon" style="margin-left: 30px;"><Filter /></el-icon>
              </template>
              <el-input 
                v-model.number="queryParams.successNumber" 
                placeholder="请输入完成数量" 
                clearable
                width="200"
                @keyup.enter="handleSearch"
              />
              <div style="text-align: right; margin-top: 10px;">
                <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
                <el-button size="small" @click="clearSearch('successNumber')">重置</el-button>
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="numberSum" label="排产总数" align="left" width="120"></el-table-column>
      <el-table-column prop="saleName" label="销售人员" align="left" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="left" :show-overflow-tooltip="true">
        <!-- <template #header>
          <div class="header-search-container">
            <span>创建时间</span>
            <el-popover placement="bottom" width="400" trigger="click">
              <template #reference>
                <el-icon class="search-icon" style="margin-left: 30px;"><Filter /></el-icon>
              </template>
              <el-date-picker
                v-model="queryParams.createTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
              <div style="text-align: right; margin-top: 10px;">
                <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
                <el-button size="small" @click="clearSearch('createTime')">重置</el-button>
              </div>
            </el-popover>
          </div>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="left">
        <template #default="scope">
          <el-link type="primary" class="ml5" @click="handleViewDetail(scope.row)">查看详情</el-link>
          <!-- 进行中显示撤回按钮 -->
          <template v-if="scope.row.status === 1">
            <el-link type="danger" class="ml5" @click="handleWithdraw(scope.row)">撤回</el-link>
          </template>
          <!-- 未开始显示查看撤回申请按钮 -->
          <template v-else-if="scope.row.status === 0">
            <el-link type="primary" class="ml5" @click="handleViewWithdrawApplication(scope.row)">查看撤回申请</el-link>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 20px; justify-content: flex-end;"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 撤回弹窗组件 -->
    <WithdrawComponent
      v-model="withdrawVisible"
      :row-data="selectedRow"
      @success="handleWithdrawSuccess"
      @cancel="handleWithdrawCancel"
    />

    <!-- 查看撤回申请弹窗组件 -->
    <WidthdrawApplicationComponent
      v-model="viewWithdrawVisible"
      :application-data="selectedRow"
      @close="handleViewWithdrawClose"
    />
  </div>
</template>

<script setup name="scheduling">
// 引入需要的模块
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import WithdrawComponent from './withdraw.vue'
import WidthdrawApplicationComponent from './widthdrawApplication.vue'
import { useRouter } from 'vue-router' // 新增：引入路由
import {
  getProductionOrder
} from '@/api/production'

// 创建路由实例
const router = useRouter() // 新增：创建路由实例

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyWord: ''
})

// 数据总数
const total = ref(0)
// 加载状态
const loading = ref(false)
// 状态统计
const notStartedCount = ref(2)
const inProgressCount = ref(5)
const successNumber = ref(1)

// 表格数据
const productionList = ref([])

// 弹窗状态
const withdrawVisible = ref(false)
const viewWithdrawVisible = ref(false)
const selectedRow = ref({})

// 模拟数据
const originalData = [
  {
    dno: 'XQ001',
    dname: '需求名称1',
    cname: '和公司的合同1',
    materialName: '卷帘门',
    productionNumber: 3,
    successNumber: 1,
    numberSum: 100,
    saleName: '李四(lisi)',
    createTime: '2025-03-31 15:52:02',
    status: 0, // 0: 未开始, 1: 进行中, 2: 已完成
    storageStatus: 0, // 入库状态，不显示在表头
    withdrawReason: '客户需求变更，需要重新排产', // 新增：撤回原因
    approvalFlow: [ // 新增：审批流程
      {
        title: '提交申请',
        content: '提交撤回申请等待审批',
        approver: '张三(zhangsan)',
        time: '2025-03-31 10:30:00',
        status: 'approved'
      },
      {
        title: '部门审批',
        content: '同意撤回申请',
        approver: '王五(wangwu)',
        time: '2025-03-31 14:20:00',
        status: 'approved'
      },
      {
        title: '最终审批',
        content: '等待审批',
        approver: '赵六(zhaoliu)',
        time: '2025-03-31 15:00:00',
        status: 'pending'
      }
    ]
  },
  {
    dno: 'XQ002',
    dname: '需求名称2',
    cname: '和公司的合同1',
    materialName: '卷帘门',
    productionNumber: 3,
    successNumber: 3,
    numberSum: 200,
    saleName: '李四(lisi)',
    createTime: '2025-03-31 15:52:02',
    status: 2,
    storageStatus: 1,
    withdrawReason: '',
    approvalFlow: []
  },
  {
    dno: 'XQ003',
    dname: '需求名称3',
    cname: '另一个合同',
    materialName: '防火门',
    productionNumber: 14,
    successNumber: 0,
    numberSum: 40,
    saleName: '王五(wangwu)',
    createTime: '2025-03-30 15:52:02',
    status: 1,
    storageStatus: 2,
    withdrawReason: '',
    approvalFlow: []
  }
]

// 获取排产列表
const getProductionList = () => {
  loading.value = true
  getProductionOrder(queryParams).then(res => {
    loading.value = false
    productionList.value = res.data?.list || [];
    total.value = res.data?.total || 0;
  }).catch(() => {
    productionList.value = [];
    total.value = 0;
  });
}

// 初始化
onMounted(() => {
  getProductionList()
})

// 搜索
function handleSearch() {
  queryParams.pageNum = 1
  getProductionList()
}
// 清空搜索
function clearSearch(field) {
  queryParams[field] = ''
  getProductionList()
}

// 分页大小改变
function handleSizeChange(val) {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  getproductionList()
}

// 当前页码改变
function handleCurrentChange(val) {
  queryParams.pageNum = val
  getproductionList()
}

// 修改查看详情函数
function handleViewDetail(row) {
  console.log('查看详情:', row)
  // 跳转到详情页面
  router.push({
    path: `/production/scheduleDetail/index/${row.deId}`
  })
}

// 处理撤回
function handleWithdraw(row) {
  selectedRow.value = { ...row }
  withdrawVisible.value = true
}

// 处理查看撤回申请
function handleViewWithdrawApplication(row) {
  selectedRow.value = { ...row }
  viewWithdrawVisible.value = true
}

// 撤回成功回调
function handleWithdrawSuccess(formData) {
  console.log('撤回申请成功:', formData)
  // 更新数据源中的撤回原因
  const index = originalData.findIndex(item => item.dno === formData.dno)
  if (index !== -1) {
    originalData[index].withdrawReason = formData.withdrawReason
    // 重置审批流程
    originalData[index].approvalFlow = [
      {
        title: '提交申请',
        content: '提交撤回申请等待审批',
        approver: '当前用户',
        time: new Date().toLocaleString('zh-CN'),
        status: 'pending'
      }
    ]
    // 更新状态为未开始
    originalData[index].status = 0
  }
  // 刷新列表
  getproductionList()
  ElMessage.success('撤回申请已提交')
}

// 撤回取消回调
function handleWithdrawCancel() {
  selectedRow.value = {}
}

// 查看撤回申请关闭回调
function handleViewWithdrawClose() {
  selectedRow.value = {}
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  box-sizing: border-box;
}

.header-bar {
  margin-bottom: 10px;
  overflow: hidden;
}

.status-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.status-card {
  flex: 1;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-content {
  text-align: center;
}

.status-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.status-count {
  font-size: 24px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.status-card.not-started .status-count {
  color: red;
}
.status-card.not-started .status-title {
  color: red;
}

.status-card.in-progress .status-count {
  color: orange;
}
.status-card.in-progress .status-title {
  color: orange;
}

.status-card.completed .status-count {
  color: green;
}
.status-card.completed .status-title {
  color: green;
}

.header-icon {
  font-size: 14px;
  color: #909399;
  margin-left: 5px;
}

.ml5 {
  margin-left: 15px;
}

:deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap;
  margin-top: 20px;
}
</style>
